/* eslint-disable @typescript-eslint/no-unused-expressions */
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useMemo, useState } from 'react'
import { Button, Card, Form, Input, Modal, Select, Space, Table, Tag, Popover, Checkbox, message, TreeSelect } from 'antd'
import { ReloadOutlined, SearchOutlined, PlusOutlined, DownloadOutlined, UploadOutlined } from '@ant-design/icons'
import Pagination from '../../components/Pagination';

interface GoodsRow {
  id: number
  code: string
  name: string
  status: '启用' | '停用'
  type: string      // 叶子类型（如 智能手机/功能手机/智能电视）
  categoryPath: string // 层级路径（如 电子产品/手机/智能手机）
  model: string
  unit: string
  unitTips: string[]
  barcodes: string[]
  supplier: string
  customer: string
  inPrice: number
  outPrice: number
  order: number
}

const generateMock = (n: number): GoodsRow[] =>
  Array.from({ length: n }, (_, i) => {
    const leafs = ['智能手机', '功能手机', '智能电视', '显示器', '裤子', '裙子']
    const leaf = leafs[i % leafs.length]
    let path = ''
    if (leaf === '智能电视') path = '电子产品/电视/智能电视'
    else if (leaf === '显示器') path = '电子产品/显示器'
    else if (leaf === '裤子') path = '服装/男装/裤子'
    else if (leaf === '裙子') path = '服装/连衣裙/裙子'
    else path = `电子产品/手机/${leaf}`
    return {
      id: i + 1,
      code: `HPDH${1000 + i}`,
      name: ['苹果手机', '电视机', '咖啡机', '空调', '洗衣机', '电脑', '手表', '钢笔', '餐具套装', '运动鞋'][i % 10],
      status: i % 7 === 1 ? '停用' : '启用',
      type: leaf,
      categoryPath: path,
      model: ['blue', 'pro', 'mini'][i % 3],
      unit: ['个', '件', '箱'][i % 3],
      unitTips: ['个', '件', '箱'],
      barcodes: [`0000${25 + i}`, `0000${26 + i}`, `0000${27 + i}`],
      supplier: '供应商',
      customer: '客户',
      inPrice: 100,
      outPrice: 200,
      order: (i % 10) + 1,
    }
  })

export default function Message() {
  const [form] = Form.useForm()
  const [data, setData] = useState<GoodsRow[]>(() => generateMock(100))
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const [page, setPage] = useState({ current: 1, pageSize: 10 })
  const [query, setQuery] = useState<any>({})

  // 弹窗
  const [modalOpen, setModalOpen] = useState(false)
  const [editing, setEditing] = useState<GoodsRow | null>(null)
  const [modalForm] = Form.useForm<GoodsRow>()

  // 过滤
  const filtered = useMemo(() => {
    const { keyword, status, category, showStock } = query
    return data.filter((r) => {
      const hitKw = keyword ? r.name.includes(keyword) || r.code.includes(keyword) : true
      const hitStatus = status ? r.status === status : true
      const hitCat = category ? ((r.categoryPath || r.type || '').includes(category)) : true
      const hitStock = showStock ? true : true
      return hitKw && hitStatus && hitCat && hitStock
    })
  }, [data, query])

  const openAdd = () => {
    setEditing(null)
    modalForm.resetFields()
    // 设置一些默认值，避免未填导致渲染异常
    modalForm.setFieldsValue({ status: '启用', unit: '个', inPrice: 0, outPrice: 0, order: 1 })
    setModalOpen(true)
  }

  const openEdit = (row: GoodsRow) => {
    setEditing(row)
    modalForm.setFieldsValue(row)
    setModalOpen(true)
  }

  const handleDelete = (id: number) => {
    Modal.confirm({
      title: '确定删除该记录吗？',
      onOk: () => {
        setData((prev) => prev.filter((x) => x.id !== id))
        message.success('删除成功')
      }
    })
  }

  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) return message.info('请先选择记录')
    Modal.confirm({
      title: `确定删除选中的 ${selectedRowKeys.length} 条记录吗？`,
      onOk: () => {
        setData((prev) => prev.filter((x) => !selectedRowKeys.includes(x.id)))
        setSelectedRowKeys([])
        message.success('批量删除成功')
      }
    })
  }

  const handleCopy = (row: GoodsRow) => {
    const maxId = Math.max(...data.map((d) => d.id))
    const copy: GoodsRow = { ...row, id: maxId + 1, code: `${row.code}_COPY` }
    setData((prev) => [copy, ...prev])
    message.success('已复制一条新记录')
  }

  const handleModalOk = () => {
    modalForm.validateFields().then((values) => {
      if (editing) {
        // 编辑：也做一次兜底，防止缺字段
        const safe: GoodsRow = {
          id: editing.id,
          code: values.code,
          name: values.name,
          status: (values as any).status || '启用',
          type: (values as any).type || '',
          categoryPath: (editing as any).categoryPath || (values as any).type || '',
          model: (values as any).model || '',
          unit: (values as any).unit || '个',
          unitTips: editing.unitTips || ['个', '件', '箱'],
          barcodes: editing.barcodes || [],
          supplier: (editing as any).supplier || '供应商',
          customer: (editing as any).customer || '客户',
          inPrice: Number((values as any).inPrice ?? editing.inPrice ?? 0),
          outPrice: Number((values as any).outPrice ?? editing.outPrice ?? 0),
          order: Number((values as any).order ?? editing.order ?? 1),
        }
        setData((prev) => prev.map((x) => (x.id === editing.id ? safe : x)))
        message.success('编辑成功')
      } else {
        const maxId = Math.max(...data.map((d) => d.id))
        const safe: GoodsRow = {
          id: maxId + 1,
          code: (values as any).code,
          name: (values as any).name,
          status: (values as any).status || '启用',
          type: (values as any).type || '',
          categoryPath: (values as any).type || '',
          model: (values as any).model || '',
          unit: (values as any).unit || '个',
          unitTips: ['个', '件', '箱'],
          barcodes: [],
          supplier: '供应商',
          customer: '客户',
          inPrice: Number((values as any).inPrice ?? 0),
          outPrice: Number((values as any).outPrice ?? 0),
          order: Number((values as any).order ?? 1),
        }
        setData((prev) => [safe, ...prev])
        message.success('新增成功')
      }
      setModalOpen(false)
    })
  }

  // 导出CSV（简单实现）
  const handleExport = () => {
    const headers = ['序号', '货品编号', '货品名称', '状态', '货品类型', '规格型号', '单位', '供应商', '客户名称', '入库参考价', '出库参考价', '显示顺序']
    const rows = data.map((r) => [r.id, r.code, r.name, r.status, r.type, r.model, r.unit, r.supplier, r.customer, r.inPrice, r.outPrice, r.order])
    const csv = [headers, ...rows].map((arr) => arr.join(',')).join('\n')
    const blob = new Blob(["\uFEFF" + csv], { type: 'text/csv;charset=utf-8;' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '货品信息.csv'
    a.click()
    URL.revokeObjectURL(url)
  }

  const columns = [
    { title: '序号', dataIndex: 'id', width: 70, align: 'center', fixed: 'left' as const },
    { title: '货品编号', dataIndex: 'code', width: 120, fixed: 'left' as const, render: (v: string) => <a>{v}</a> },
    { title: '货品名称', dataIndex: 'name', width: 140, fixed: 'left' as const },
    { title: '状态', dataIndex: 'status', width: 80, fixed: 'left' as const, render: (v: GoodsRow['status']) => <Tag color={v === '启用' ? 'green' : 'default'}>{v}</Tag> },
    { title: '货品类型', dataIndex: 'type', width: 120 },
    { title: '规格型号', dataIndex: 'model', width: 100 },
    { title: '单位', dataIndex: 'unit', width: 100, render: (_: any, row: GoodsRow) => (<Popover content={<div>{row.unitTips.map((t) => <div key={t}>{t}</div>)}</div>}><span>{row.unit}</span></Popover>) },
    { title: '条码', dataIndex: 'barcodes', width: 150, render: (codes: string[]) => (<Popover content={<div>{codes.map((c) => <div key={c}>{c}</div>)}</div>}><a>查看</a></Popover>) },
    { title: '供应商', dataIndex: 'supplier', width: 100 },
    { title: '客户名称', dataIndex: 'customer', width: 100 },
    { title: '入库参考价/元', dataIndex: 'inPrice', width: 130, align: 'right', render: (v: number) => v.toFixed(2) },
    { title: '出库参考价/元', dataIndex: 'outPrice', width: 130, align: 'right', render: (v: number) => v.toFixed(2) },
    { title: '显示顺序', dataIndex: 'order', width: 100, align: 'center' },
    {
      title: '操作', key: 'op', width: 140, fixed: 'right' as const, render: (_: any, row: GoodsRow) => (
        <Space>
          <a onClick={() => openEdit(row)}>编辑</a>
          <a onClick={() => handleDelete(row.id)}>删除</a>
        </Space>
      )
    }
  ]

  return (
    <div className="goods-message-page">
      <Card className="search-filter" variant="outlined">
        <Form form={form} layout="inline" className="filter-form" initialValues={{ showStock: false }}>
          <Form.Item label="货品" name="keyword">
            <Input allowClear placeholder="请输入货品名称/编号" style={{ width: 240 }} />
          </Form.Item>
          <Form.Item label="状态" name="status">
            <Select allowClear placeholder="请选择" style={{ width: 120 }} options={[{ label: '启用', value: '启用' }, { label: '停用', value: '停用' }]} />
          </Form.Item>
          <Form.Item label="货品类型" name="category">
            <TreeSelect
              allowClear
              placeholder="请选择"
              style={{ width: 180 }}
              treeDefaultExpandAll
              treeData={[
                {
                  title: '电子产品', value: '电子产品', children: [
                    {
                      title: '手机', value: '手机', children: [
                        { title: '智能手机', value: '智能手机' },
                        { title: '功能手机', value: '功能手机' },
                      ]
                    },
                    {
                      title: '电视', value: '电视', children: [
                        { title: '智能电视', value: '智能电视' },
                      ]
                    },
                    { title: '显示器', value: '显示器' },
                  ]
                },
                {
                  title: '服装', value: '服装', children: [
                    { title: '男装', value: '男装', children: [{ title: '裤子', value: '裤子' }] },
                    { title: '连衣裙', value: '连衣裙', children: [{ title: '裙子', value: '裙子' }] },
                  ]
                }
              ]}
            />
          </Form.Item>
          <Form.Item name="showStock" valuePropName="checked">
            <Checkbox>显示库存货品</Checkbox>
          </Form.Item>
          <Space className="filter-actions">
            <Button icon={<ReloadOutlined />} onClick={() => { form.resetFields(); setQuery({}); setPage({ current: 1, pageSize: page.pageSize }) }}>重置</Button>
            <Button type="primary" icon={<SearchOutlined />} onClick={() => { setQuery(form.getFieldsValue()); setPage({ current: 1, pageSize: page.pageSize }) }}>查询</Button>
          </Space>
        </Form>
      </Card>

      <Card className="action-buttons" variant="outlined">
        <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={openAdd}>新增</Button>
          <Button onClick={() => { const first = filtered[0]; first && openEdit(first) }}>编辑</Button>
          <Button danger onClick={handleBatchDelete}>删除</Button>
          <Button onClick={() => { const first = filtered[0]; first && handleCopy(first) }}>复制</Button>
          <Button icon={<DownloadOutlined />} onClick={handleExport}>导出</Button>
          <Button icon={<UploadOutlined />} onClick={() => message.info('导入占位：可接入文件选择与解析')}>导入</Button>
          <Button onClick={() => message.success('已刷新')}>刷新</Button>
        </Space>
      </Card>

      <Card className="store-table" variant="outlined">
        <Table
          rowKey="id"
          size="middle"
          columns={columns as any}
          dataSource={filtered.slice((page.current - 1) * page.pageSize, page.current * page.pageSize)}
          pagination={false}
          rowSelection={{ selectedRowKeys, onChange: setSelectedRowKeys }}
          scroll={{ x: 1600 }}
        />
        <Pagination
          current={page.current}
          pageSize={page.pageSize}
          total={filtered.length}
          onChange={(current, pageSize) => setPage({ current, pageSize: pageSize || page.pageSize })}
        />
      </Card>

      <Modal
        title={editing ? '编辑货品' : '新增货品'}
        open={modalOpen}
        destroyOnHidden
        onCancel={() => setModalOpen(false)}
        onOk={handleModalOk}
      >
        <Form form={modalForm} layout="vertical">
          <Form.Item label="货品编号" name="code" rules={[{ required: true, message: '请输入货品编号' }]}>
            <Input />
          </Form.Item>
          <Form.Item label="货品名称" name="name" rules={[{ required: true, message: '请输入货品名称' }]}>
            <Input />
          </Form.Item>
          <Form.Item label="状态" name="status" rules={[{ required: true }]} initialValue={'启用'}>
            <Select options={[{ label: '启用', value: '启用' }, { label: '停用', value: '停用' }]} />
          </Form.Item>
          <Form.Item label="货品类型" name="type">
            <Input />
          </Form.Item>
          <Form.Item label="规格型号" name="model"><Input /></Form.Item>
          <Form.Item label="单位" name="unit"><Input /></Form.Item>
          <Form.Item label="入库参考价" name="inPrice"><Input type="number" /></Form.Item>
          <Form.Item label="出库参考价" name="outPrice"><Input type="number" /></Form.Item>
          <Form.Item label="显示顺序" name="order"><Input type="number" /></Form.Item>
        </Form>
      </Modal>
    </div>
  )
}